package com.tencent.yolov8ncnn;

import android.Manifest;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.usb.UsbDevice;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
//import android.support.annotation.NonNull;
//import android.support.annotation.Nullable;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.herohan.uvcapp.CameraHelper;
import com.herohan.uvcapp.ICameraHelper;
import com.herohan.uvcapp.ImageCapture;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.XXPermissions;
import com.serenegiant.utils.FileUtils;
import com.serenegiant.utils.UriHelper;
import com.serenegiant.widget.AspectRatioSurfaceView;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

public class UsbIndividuallyActivity extends AppCompatActivity {
    private TextView openCamera;
    private ICameraHelper mCameraHelper;
    private LinearLayout takepicture;
    private Yolov8Ncnn yolov8ncnnUv=new Yolov8Ncnn();
    private Yolov8Ncnn yolov8ncnnUnit=new Yolov8Ncnn();
    private int current_model = 0;
    private int current_cpugpu = 1;
    private ImageView pictureAnalysis;
    private int flag=0;//进行检测的项目 0为油脂，1为角质，2为敏感度，3为直径，4为密度
    private int number_picture;
    private LinearLayout reset;
    private TextView suggestion;
    private TextView serverity;
    private TextView describe;
    private TextView serverity_number;
    private LinearLayout oilDetect;
    private LinearLayout druffDetect;
    private LinearLayout sensitiveDetect;
    private LinearLayout diameterDetect;
    private LinearLayout densityDetect;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.usb_detect);
        openCamera= (TextView) findViewById(R.id.danxiang_tv_back);
        takepicture= (LinearLayout) findViewById(R.id.tv_takepicture);
        pictureAnalysis= (ImageView) findViewById(R.id.picture_analysis);
        suggestion=findViewById(R.id.suggestion);
        serverity=findViewById(R.id.serverity);
        describe=findViewById(R.id.describe);
        serverity_number=findViewById(R.id.serverity_number);
        reset=findViewById(R.id.reset);
        oilDetect=findViewById(R.id.scalp_oil);
        druffDetect=findViewById(R.id.scalp_druff);
        sensitiveDetect=findViewById(R.id.scalp_sensitive);
        diameterDetect=findViewById(R.id.scalp_diameter);
        densityDetect=findViewById(R.id.density);
        number_picture=0;
        OnEvent();
        reload();
    }
    private void OnEvent(){
        openCamera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final String[] permission = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};
                XXPermissions.with(UsbIndividuallyActivity.this)
                        .permission(permission)
                        .request(new OnPermissionCallback() {
                            @Override
                            public void onGranted(List<String> permissions, boolean all) {
                                if (all) {
                                    initCameraHelper();
                                    initCameraView();
                                } else {
//                                    toast("权限申请失败，无法打开相机，保存图片");
                                    finish();
                                }
                            }

                            @Override
                            public void onDenied(List<String> permissions, boolean never) {
                                if (never) {
                                    XXPermissions.startPermissionActivity(UsbIndividuallyActivity.this, permission);
                                } else {
                                }
                            }
                        });
            }
        });
        takepicture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                takePicture();
            }
        });
        reset.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pictureAnalysis.setVisibility(View.INVISIBLE);
            }
        });
        oilDetect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                flag=0;
            }
        });
        druffDetect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                flag=1;
            }
        });
        sensitiveDetect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                flag=2;
            }
        });
        diameterDetect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                flag=3;
            }
        });
        densityDetect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                flag=4;
            }
        });

    }
    private void reload(){
        boolean ret_init=yolov8ncnnUv.loadModel(getAssets(),0,current_cpugpu);
        if(!ret_init){
            Log.e("UsbIndividuallyActivity","yolov8ncnnUv loadModel failed");
        }
        ret_init=yolov8ncnnUnit.loadModel(getAssets(),1,current_cpugpu);
        if(!ret_init){
            Log.e("UsbIndividuallyActivity","yolov8ncnnUnit loadModel failed");
        }
    }
//    public void toast(String Messsage) {
//        com.blankj.utilcode.util.ToastUtils.showShort(Messsage);
//    }
    public void initCameraHelper() {
        if (mCameraHelper == null) {
            mCameraHelper = new CameraHelper();
            final AspectRatioSurfaceView cameraView= (AspectRatioSurfaceView) findViewById(R.id.camera_view);
            mCameraHelper.setStateCallback(new ICameraHelper.StateCallback() {
                @Override
                public void onAttach(UsbDevice device) {
                    //这句话注释掉了，不然每次都默认启动同一个摄像头
//                    mCameraHelper.selectDevice(device);
                }

                @Override
                public void onDeviceOpen(UsbDevice device, boolean isFirstOpen) {
                    mCameraHelper.openCamera();
                }

                @Override
                public void onCameraOpen(UsbDevice device) {
                    mCameraHelper.getUVCControl().setSharpness(0);
                    mCameraHelper.startPreview();

                    mCameraHelper.addSurface(cameraView.getHolder().getSurface(), false);

                }

                @Override
                public void onCameraClose(UsbDevice device) {
                    if (mCameraHelper != null) {
                        mCameraHelper.removeSurface(cameraView.getHolder().getSurface());
                    }
                }

                @Override
                public void onDeviceClose(UsbDevice device) {
                }

                @Override
                public void onDetach(UsbDevice device) {
                }

                @Override
                public void onCancel(UsbDevice device) {
                }

            });
        }
    }
    List<String> mSelectsImageList = new ArrayList<>();
    private void takePicture() {
        //ProgressUtils.showDialog(this, "图片拍摄中");
        if (mCameraHelper == null) return;
        //设置视图片抓拍全局参数（非必须，可以不设置，使用默认值）
        mCameraHelper.setImageCaptureConfig(
                mCameraHelper.getImageCaptureConfig().setCaptureMode(ImageCapture.CAPTURE_MODE_MAXIMIZE_QUALITY));

        //设置需要保存图片文件
        File file = FileUtils.getCaptureFile(this, Environment.DIRECTORY_DCIM, ".jpg");
        ImageCapture.OutputFileOptions options =
                new ImageCapture.OutputFileOptions.Builder(file).build();

        //进行图片抓拍
        mCameraHelper.takePicture(options, new ImageCapture.OnImageCaptureCallback() {
            //图片抓拍成功
            @Override
            public void onImageSaved(@NonNull ImageCapture.OutputFileResults outputFileResults) {
//                toast(UriHelper.getPath(TakePictureActivity.this, outputFileResults.getSavedUri()));
                FileInputStream fis = null;
                try {
                    fis = new FileInputStream(UriHelper.getPath(UsbIndividuallyActivity.this, outputFileResults.getSavedUri()));
                } catch (FileNotFoundException e) {
                    throw new RuntimeException(e);
                }
                Bitmap bitmap = BitmapFactory.decodeStream(fis);
                Bitmap saveBitmap=bitmap;

                final String filePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getPath() + "/" + getString(R.string.app_name) + "/";
                final String photoName = "crop_" + System.currentTimeMillis();
                ViewSaveImageUtils.savePhotoToSDCard(saveBitmap, filePath, photoName);

                mSelectsImageList.clear();
                mSelectsImageList.add(filePath + photoName + ".jpg");
//                numberstep.setText(Integer.toString(step));
//                mSelectsImageList.add(UriHelper.getPath(TakePictureActivity.this, outputFileResults.getSavedUri()));
//                Log.e(TAG, "uploadImage12 --->: " + mSelectsImageList.size());
//                ProgressUtils.dissDialog();
                //图片上传得到分析结果

                // 操作客户那边的接口流程
                if (mSelectsImageList.size() > 0) {
                    Bitmap outputBmp = Bitmap.createBitmap(saveBitmap.getWidth(), saveBitmap.getHeight(), Bitmap.Config.ARGB_8888);
                    //yolov8ncnn.usbInfer(saveBitmap,outputBmp);
//                    OilReturn tmp=yolov8ncnn.usbInfer1(saveBitmap,outputBmp);
//                    suggestion.setText(tmp.suggestion);
//                    describe.setText(tmp.describe);
//                    serverity.setText(tmp.severity);
//                    serverity_number.setText(String.valueOf(tmp.level));
//                    status.setText(String.valueOf(tmp.status_code));
                    if(flag==0&&number_picture==0){
                        OilReturn tmp= yolov8ncnnUv.surfaceOilDetect(saveBitmap,outputBmp);
                        suggestion.setText(tmp.suggestion);
                        describe.setText(tmp.describe);
                        serverity.setText(tmp.severity);
                        serverity_number.setText(String.valueOf(tmp.level));
                        number_picture++;
                    } else if (flag==0&&number_picture==1) {
                        OilReturn tmp= yolov8ncnnUv.oilanddruffDetect(saveBitmap,outputBmp,0);
                        number_picture=0;
                    } else if (flag==1){
                        OilReturn tmp= yolov8ncnnUv.oilanddruffDetect(saveBitmap,outputBmp,1);
                        suggestion.setText(tmp.suggestion);
                        describe.setText(tmp.describe);
                        serverity.setText(tmp.severity);
                        serverity_number.setText(String.valueOf(tmp.level));
                    } else if(flag==2){
                        seneitiveReturn tmp=yolov8ncnnUv.sensitiveDetect(saveBitmap,outputBmp);
                        suggestion.setText(tmp.suggestion);
                        describe.setText(tmp.describe);
                        serverity.setText(tmp.severity);
                        serverity_number.setText(String.valueOf(tmp.level));
                    } else if(flag==3){
                        TotalInfo tmp= yolov8ncnnUnit.densityanddiameterDetect(saveBitmap,outputBmp,0);
                        suggestion.setText(tmp.suggestion);
                        describe.setText(tmp.describe);
                        serverity.setText(tmp.severity);
                        serverity_number.setText(String.valueOf(tmp.level));
                    } else if(flag==4){
                        TotalInfo tmp= yolov8ncnnUnit.densityanddiameterDetect(saveBitmap,outputBmp,1);
                        suggestion.setText(tmp.suggestion);
                        describe.setText(tmp.describe);
                        serverity.setText(tmp.severity);
                        serverity_number.setText(String.valueOf(tmp.level));
                    }
                    pictureAnalysis.setVisibility(View.VISIBLE);
                    final String filePath1=Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getPath()+"/"+getString(R.string.app_name)+"/";
                    final String photoName1="crop_"+System.currentTimeMillis();
                    ViewSaveImageUtils.savePhotoToSDCard(outputBmp,filePath1,photoName1);
                    pictureAnalysis.setImageURI(Uri.parse(filePath1+photoName1+".jpg"));

                } else {
                    //toast("拍摄失败");
                }
            }

            //图片抓拍出现错误
            @Override
            public void onError(int imageCaptureError, @NonNull String message, @Nullable Throwable cause) {
                //toast(message);
            }
        });
    }

    private void initCameraView() {
        //设置SurfaceView的Surface监听回调
        AspectRatioSurfaceView cameraView= (AspectRatioSurfaceView) findViewById(R.id.camera_view);
        cameraView.getHolder().addCallback(new SurfaceHolder.Callback() {

            //创建了新的Surface
            @Override
            public void surfaceCreated(@NonNull SurfaceHolder holder) {
                if (mCameraHelper != null) {
                    //添加预览Surface
                    mCameraHelper.addSurface(holder.getSurface(), false);
                }
            }

            //Surface发生了改变
            @Override
            public void surfaceChanged(@NonNull SurfaceHolder holder, int format, int width, int height) {
            }

            //销毁了原来的Surface
            @Override
            public void surfaceDestroyed(@NonNull SurfaceHolder holder) {
                if (mCameraHelper != null) {
                    //移除预览Surface
                    mCameraHelper.removeSurface(holder.getSurface());
                }
            }
        });
        if (mCameraHelper != null) {
            final List<UsbDevice> list = mCameraHelper.getDeviceList();
            //根据关键字获取相应位置的摄像头
            //USB名称为：USB Camera1-Front VID：0BDA : PID: 3035 前面
            //USB Camera2-Brak VID：0BDB : PID: 3036 后面
            //USB Camera3-Top VID：0BDC: PID: 3037 头顶
            String mProductNameKeywords = "PF01";
            if (StringUtils.isEmpty(mProductNameKeywords)) {
                //toast("未识别到有效设备");
                finish();
            } else {
                for (int i = 0; i < list.size(); i++) {
                    if (list.get(i).getProductName().contains(mProductNameKeywords)) {
                        mCameraHelper.selectDevice(list.get(i));
                        break;
                    }
                }
            }


        }

    }
    private void clearCameraHelper() {
        if (mCameraHelper != null) {
            mCameraHelper.release();
            mCameraHelper = null;
        }
    }
    protected void onStop() {
        super.onStop();
        clearCameraHelper();

    }
}
